package com.you.concurrent.synchronize;

public class SynchronziedDemo {

    static int num = 0;

    public synchronized void count1() {
        for (int i = 0; i < 100; i++) {
            try {
                Thread.sleep(1L);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            SynchronziedDemo.num++;
        }
        System.out.println(Thread.currentThread().getName() + "-----end!");
    }

    public void count2() {
        synchronized (this) {
            for (int i = 0; i < 100; i++) {
                try {
                    Thread.sleep(1L);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                SynchronziedDemo.num++;
            }
            System.out.println(Thread.currentThread().getName() + "-----end!");
        }
    }

    public static synchronized void count3() {
        for (int i = 0; i < 100; i++) {
            try {
                Thread.sleep(1L);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            SynchronziedDemo.num++;
        }
        System.out.println(Thread.currentThread().getName() + "-----end!");
    }

    public void count4() {
        synchronized (SynchronziedDemo.class) {
            for (int i = 0; i < 100; i++) {
                try {
                    Thread.sleep(1L);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                SynchronziedDemo.num++;
            }
            System.out.println(Thread.currentThread().getName() + "-----end!");
        }
    }

    static class CountThread implements Runnable {

        private SynchronziedDemo synchronziedDemo = null;

        public CountThread(SynchronziedDemo synchronziedDemo) {
            this.synchronziedDemo = synchronziedDemo;
        }

        @Override
        public void run() {
            //synchronziedDemo.count1();
            //synchronziedDemo.count2();
            //synchronziedDemo.count3();
            synchronziedDemo.count4();
        }
    }

    public static void main(String[] args) {
        SynchronziedDemo synchronziedDemo = new SynchronziedDemo();
        for (int i = 0; i < 10; i++) {
            new Thread(new CountThread(new SynchronziedDemo())).start();
        }
        try {
            Thread.sleep(5000L);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("num=" + num);
    }
}
